#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
int main()
{
    int pipefd[2];
    if(pipe(pipefd) == -1)
    {
        cerr << "pipe open fault" << endl;
        return 1;
    }
    pid_t pid = fork();
    if(pid < 0)
    {
        cerr << "fork fault" << endl;
        return 1;
    }
    else if(pid == 0)
    {
        //子进程
        close(pipefd[1]);//子进程关闭写端，子进程读
        char buffer[1024] = {0};
        int cnt = read(pipefd[0],buffer,1023);
        buffer[cnt + 1] = 0;
        cout << buffer << endl;
        exit(0);
    }
    
    //父进程
    close(pipefd[0]);//父进程关闭读端，父进程写
    string str;
    getline(cin,str);
    write(pipefd[1],str.c_str(),str.size());
    if(waitpid(pid,nullptr,0))
        cout << "父子进程间完成匿名管道通信" << endl;
    return 0;
}